package com.ipan.weixin.msg.general;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.Element;

/**
 * 图片消息
 * 
 * @author iPan
 * @version 2013-12-23
 */
public class ImageMsg extends PlainMsg {
	
	/** serialVersionUID */
	private static final long serialVersionUID = -8778620867763689443L;
	
	/** 图片链接 */
	private String picUrl;
	
	/** 图片消息媒体id（必须） */
	private String mediaId;
	
	public ImageMsg() {
		super(TransportType.RECEIVE_AND_REPLY);
	}
	
	public ImageMsg(Document doc) {
		this();
		fromXml(doc);
	}

	public String getPicUrl() {
		return picUrl;
	}

	public void setPicUrl(String picUrl) {
		this.picUrl = picUrl;
	}

	public String getMediaId() {
		return mediaId;
	}

	public void setMediaId(String mediaId) {
		this.mediaId = mediaId;
	}

	@Override
	public void fromXml(Document doc) {
		if (doc == null) {
			return ;
		}
		
		super.fromXml(doc);
		Element root = doc.getRootElement();
		this.picUrl = root.elementTextTrim(EL_PIC_URL);
		this.mediaId = root.elementTextTrim(EL_MEDIA_ID);
	}

	@Override
	public String toXml(boolean nonEmpty) {
		StringBuilder buf = new StringBuilder("<xml>");
		buf.append(super.toXml(nonEmpty));
		buf.append(wrapElementHead(EL_MSG_TYPE)).append(TYPE_IMAGE).append(wrapElementEnd(EL_MSG_TYPE));
		if (nonEmpty) {
			buf.append(wrapElementHead(EL_IMAGE));
			if (StringUtils.isNotEmpty(this.mediaId)) {
				buf.append(wrapElementHead(EL_MEDIA_ID)).append(this.mediaId).append(wrapElementEnd(EL_MEDIA_ID));
			}
			buf.append(wrapElementEnd(EL_IMAGE));
		} else {
			buf.append(wrapElementHead(EL_IMAGE));
			buf.append(wrapElementHead(EL_MEDIA_ID)).append(getStringValue(this.mediaId)).append(wrapElementEnd(EL_MEDIA_ID));
			buf.append(wrapElementEnd(EL_IMAGE));
		}
		return buf.append("</xml>").toString();
	}
}

/*---------------------------------------------
接收：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<PicUrl><![CDATA[this is a url]]></PicUrl>
<MediaId><![CDATA[media_id]]></MediaId>
<MsgId>1234567890123456</MsgId>
</xml>

回复：
<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>12345678</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
<Image>
<MediaId><![CDATA[media_id]]></MediaId>
</Image>
</xml>
--------------------------------------------*/